package zrar.panel;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Observable;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;


import zrar.entity.AnswerPeople;
import zrar.entity.Prize;
import zrar.util.ExcelUtil;
import zrar.util.ToolUtil;
import zrar.util.SystemUtil;

public class ResultPanel extends Observable implements ActionTouchImpl {

	private static final long serialVersionUID = 1L;
	
	private JPanel thisPanel = new JPanel();

	private JLabel title_lb;
	//private JButton out_but;
	private JFileChooser fileChooser = null;

	private JScrollPane scrollPane;
	private JTable table = null;
	private DefaultTableModel defaultModel = null;
	
	private int actionNum;
	
	
	private int last_barValue =  -1; //上一次的barValue
	private int cur_barValue =  0; //当前的barValue
	private boolean isScroll=false;
	private JScrollBar scrollBar;
	
	private static final int Refresh=6;

	public ResultPanel() {
		thisPanel.setLayout(null);
		//this.setLayout(null);
		title_lb = new JLabel("中奖名单");
		
		//out_but = new JButton("保存结果");
		fileChooser = new JFileChooser("D:\\");
		File txtfile = new File(fileChooser.getCurrentDirectory().getAbsolutePath()+"/result.txt");
		fileChooser.setSelectedFile(txtfile);
		

		Object[][] p = {
				{ "  ", " ", " " }};
		String[] n = { "姓  名", "手机号码", "地                址" };
		defaultModel = new DefaultTableModel(p, n);// 创建一个默认的表格模型
		table = new JTable(defaultModel);

		table.setRowHeight(32);
		table.setFont(new Font("宋体",Font.BOLD,26));
		
		scrollPane = new JScrollPane(table);
		scrollBar = scrollPane.getVerticalScrollBar();
		
		init();
		thisPanel.add(title_lb);
		//this.add(out_but);
		thisPanel.add(scrollPane);
	}

	private void init() {
		thisPanel.setBackground(Color.WHITE);
		title_lb.setBounds(280, 20, 200, 30);
		//out_but.setBounds(550, 20, 80, 30);
		
		scrollPane.setBounds(10, 68, 690, 390);
		title_lb.setFont(new Font("楷体",Font.PLAIN,32));
		
		
		table.setPreferredScrollableViewportSize(new Dimension(400, 80));

		table.setShowGrid(false);
		table.getTableHeader().setVisible(false);

		TableColumn fourColumn = table.getColumnModel().getColumn(2);
		//fourColumn.setPreferredWidth(200);
		
		/*out_but.addMouseListener(new MouseAdapter(){
			public void mouseClicked(MouseEvent e) {
				Out_Action();
			}
		});*/
	}

	

	public void clearTable() {
		for (int index = table.getModel().getRowCount() - 1; index >= 0; index--) {
			defaultModel.removeRow(index);
		}

	}

	private AnswerPeople people;
	private List<AnswerPeople> peoples;

	public void showPrizesResult(Prize prize) {

		peoples = prize.getPersons();
		if (peoples.size() > 0) {
			// 增加 奖项 名称
			Vector<String> blank1 = new Vector<String>();
			blank1.add(" ");
			defaultModel.addRow(blank1);
			/*Vector<String> blank2 = new Vector<String>();
			blank1.add(" ");
			defaultModel.addRow(blank2);*/

			// 增加 奖项 名称
			Vector<String> vname = new Vector<String>();
			vname.add(prize.getPname());
			defaultModel.addRow(vname);

			// 增加 表格 头
			Vector<String> v = new Vector<String>();
			v.add("姓  名");
			v.add("手机号码 ");
			v.add("地    址");
			defaultModel.addRow(v);

			// 增加表格 内容
			for (int i = 0; i < peoples.size(); i++) {
				people = peoples.get(i);
				Vector<String> vpeople = new Vector<String>();
				vpeople.add(people.getPeopleName());
				vpeople.add(ToolUtil.hideTelNum(people.getPeoTel()));
				vpeople.add(ToolUtil.hideAddress(people.getAddress()));
				defaultModel.addRow(vpeople);
			}

		}

	}
	
	protected void Out_Action() {
		fileChooser.setDialogTitle("请选择 txt文件或Excle(xls文件)");
		String path = SystemUtil.result_path;
		try {
			if(path!=null&&!path.trim().isEmpty()){			
				fileChooser.setCurrentDirectory(new File(path));
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		int result = fileChooser.showSaveDialog(null);
		
		
		File file = null;
		//当用户没有选择文件,而是自己键入文件名称时,系统会自动以此文件名建立新文件.
		if (result == JFileChooser.APPROVE_OPTION) {
			
			file = fileChooser.getSelectedFile();			
			try {
				if(SystemUtil.checkFileExtendName(file.getName(), "txt")){
					ExcelUtil.writeTXT(file);
				}else if(SystemUtil.checkFileExtendName(file.getName(), "xls")){				
					ExcelUtil.writeExcel(file);				
				}else{
					JOptionPane.showMessageDialog(null, "请选择 txt文件或xls文件");
					return;
				}
			} catch (Exception e) {
				
				JOptionPane.showMessageDialog(null, "导出失败:"+e);
				e.printStackTrace();
				return;
			}
			
			SystemUtil.setResultSave(true);
			openWinFile(file);
			
		} /*else if (result == JFileChooser.CANCEL_OPTION) {
			
		}*/
	
		
	}
	
	private void openWinFile(File wfile){
		
		Object[] options = { "确定", "取消" };
		int select = JOptionPane.showOptionDialog(null, "保存成功,是否打开所在文件夹", "提示",
				JOptionPane.DEFAULT_OPTION,
				JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
				
		
		if(select ==0){
			try {
				java.awt.Desktop.getDesktop().open(wfile.getParentFile());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	/* 表格间隔色显示方法   美化表格*/
	public void sugerTableFace() {
		/*final Font fontprize =  new Font("宋体",Font.PLAIN,18);
		final Font fonttitle =  new Font("宋体",Font.PLAIN,20);
		final Font fontcontent =  new Font("宋体",Font.PLAIN,15);*/
				
		try {
			DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {
				public Component getTableCellRendererComponent(JTable table,
						Object value, boolean isSelected, boolean hasFocus,
						int row, int column) {
					String fisrtcol = (String) table.getValueAt(row, 0);
					String secondcol = (String) table.getValueAt(row, 1);
					//System.out.println("fisrtcol=="+fisrtcol+"   secondcol=="+secondcol);
					if (null!=fisrtcol && "姓  名".equals(fisrtcol)){					
						setForeground(Color.BLACK);
						setBackground(Color.YELLOW);
					}else if (null!=fisrtcol && null==secondcol){						
						setForeground(Color.RED);
						setBackground(Color.WHITE);
					}else{
						setForeground(Color.BLACK);
						setBackground(Color.WHITE);
					}
										
					if (null!=fisrtcol && null==secondcol){
						String content=" ";
						if(value!=null){
							content=value.toString();
						}
						JLabel label = new JLabel(content);
						label.setForeground(Color.RED);
						label.setFont(new Font("楷体", Font.BOLD,32));
						return label;
					}else{
						return super.getTableCellRendererComponent(table, value,
								isSelected, hasFocus, row, column);
					}
					
				}
			};
						
			for (int i = 0; i < table.getColumnCount(); i++) {
				table.getColumn(table.getColumnName(i)).setCellRenderer(tcr);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}
	
	public void startScroll(){		
		if(isScroll==false){
			isScroll=true;
			ScrollThread scrollThread = new ScrollThread();
			scrollThread.start();
		}		
	}
	
	public void stopScroll(){
		if(isScroll==true){
			isScroll=false;
		}
	}
	
	public JPanel getPane(){
		return thisPanel;
	}
	
	class ScrollThread extends Thread{

		@Override
		public void run() {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			int scroll_speed = SystemUtil.scroll;
			if(scroll_speed==0){
				isScroll=false;
			}
			
			while(isScroll){
				
				cur_barValue=scrollBar.getValue();//得到JScrollBar现在的位置
				//System.out.println("xxx last_barValue="+last_barValue+" ,cur_barValue="+cur_barValue);
				
				if(last_barValue  != cur_barValue){
					
					last_barValue = cur_barValue;
					cur_barValue = cur_barValue + 30;
					
					scrollBar.setValue(cur_barValue); //设置一个具体位置，value为具体的位置
					//table.repaint(); 
					notifyRefresh(); // 通知mainPanel类中的方法，来切换一下显示页面；防止字体滞留在页面，影响显示效果
					//table.updateUI();
					
				}else{
					scrollBar.setValue(0);
					last_barValue=-1;
					notifyRefresh();
				}
				
				try {
					Thread.sleep(scroll_speed);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
						
		}
						
	}

	public void notifyRefresh(){
		notifyTheObservers(Refresh);
	}
	
	private void notifyTheObservers(int flag){		
		setActionNum(flag);
		this.setChanged();
	    this.notifyObservers();
	}
	
	@Override
	public int getActionNum() {
		// TODO Auto-generated method stub
		return actionNum;
	}

	@Override
	public void setActionNum(int num) {
		// TODO Auto-generated method stub
		this.actionNum = num;
	}
	

}
